package nl.hr.minor.mobilelife.j1213.jlr.words;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Random;

import android.content.res.AssetManager;

public class WordTool {


	private static WordTool instance;
	private Random random;
	private StringBuilder sb;
	private LineNumberReader lineNumberReader;
	private	InputStreamReader inputStreamReader;
	private InputStream inputStream;
	public static String woord;

	private WordTool(){
		random = new Random();
		sb = new StringBuilder();
	}

	public static WordTool getInstance(){
		if(instance != null){
			return instance;
		}else{
			return instance = new WordTool();
		}
	}

	private void openResources(AssetManager assetManager, String file) {
		try{
			inputStream = assetManager.open(file);
		}catch(IOException e){}
		inputStreamReader = new InputStreamReader(inputStream);
		lineNumberReader = new LineNumberReader(inputStreamReader);
	}

	private void closeResources() {
		try {
			inputStream.close();
			inputStreamReader.close();
			lineNumberReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean check(String inWoord, AssetManager assetManager){

		for(int i = 0; i <= 28; i++){
			openResources(assetManager, i+".txt");
			String checkWoord;
			try {
				while((checkWoord = lineNumberReader.readLine())!= null){
					if(inWoord.length() == checkWoord.length()){
						if(inWoord.equals(checkWoord)){
							closeResources();
							return true;
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			closeResources();
		}
		return false;
	}


	public String shuffle(String word){
		sb.append(word);
		for(int i = 0; i < sb.length(); i ++){
			int x = random.nextInt(sb.length());
			int y = random.nextInt(sb.length());
			char save = sb.charAt(y);
			sb.setCharAt(y, sb.charAt(i));
			sb.setCharAt(i, sb.charAt(x));
			sb.setCharAt(x, save);
		}
		word = sb.toString();
		sb.setLength(0);
		return word;
	}

	public String getRandomWord(AssetManager assetManager){
		String woord = null;
		int fileNumber = random.nextInt(29);
		openResources(assetManager,fileNumber+".txt");
		int lineNumber;

		if(fileNumber == 28)
			lineNumber = random.nextInt(433);
		else
			lineNumber = random.nextInt(1251);

		boolean onLine = false;
		
		while(!onLine){
			try {
				if(lineNumberReader.getLineNumber() == lineNumber){
					WordTool.woord = woord = lineNumberReader.readLine();
					onLine = true;
				}else{
					lineNumberReader.readLine();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(woord);
		System.out.println(shuffle(woord));
		return woord;
	}
}
